package com.zhmsky.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

/**
 * @author zhmsky
 * @date 2021/12/5 11:19
 */
public class JwtUtils {
    //Token有效时间 默认为一天
    private static final int EXPIRE_TIME = 60 * 60 * 24 * 1000;
    private static final String SIGNATRUE = "$%fgg8hj%%g$%jigfdfk@@hg";

    /**
     * @param map 封装的用户登录信息
     * @return Token令牌
     * @description 生成Token令牌
     */
    public static String getToken(Map<String, String> map) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        JWTCreator.Builder builder = JWT.create();
        //负载
        map.forEach(builder::withClaim);
        // 令牌过期时间
        String Token = builder.withExpiresAt(date)
                .sign(Algorithm.HMAC256(SIGNATRUE));
        return Token;
    }

    /**
     * @param token
     * @return
     * @description 验证签名信息
     */
    public static boolean verify(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGNATRUE)).build().verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * @param token 加密令牌
     * @return 用户信息
     * @description 获取Token封装的用户信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATRUE)).build().verify(token);
    }

}
